/*
The MIT License
Copyright (c) 2019 Lehrstuhl Informatik 11 - RWTH Aachen University
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE

This file is part of embeddedRTPS.

Author: i11 - Embedded Software, RWTH Aachen University
*/

#include <string.h>
//#include "lwip/sys.h"
#include "lwip/tcpip.h"
#include "rtps/ThreadPool.h"
#include "rtps/communication/UdpDriver.h"
#include "rtps/messages/MessageFactory.h"
//#include "rtps/storages/PBufWrapper.h"
#include "rtps/utils/Log.h"
#include "rtps/utils/udpUtils.h"
#include "rtps/entities/StatelessWriter.h"

#if SLW_VERBOSE && RTPS_GLOBAL_VERBOSE
#include "rtps/utils/printutils.h"
#define SLW_LOG(...)                                                           \
  if (true) {                                                                  \
    printf("[StatelessWriter %s] ", &slw->writer.m_attributes.topicName[0]);         \
    printf(__VA_ARGS__);                                                       \
    printf("\n");                                                              \
  }
#else
#define SLW_LOG(...) //
#endif


void rtps_StatelessWriterT_destruct(void) {
  //  if(sys_mutex_valid(&m_mutex)){
  //    sys_mutex_free(&m_mutex);
  //  }
}

bool rtps_StatelessWriterT_init(struct rtps_StatelessWriter *slw, TopicData attributes,
                                           TopicKind_t topicKind,
                                           ThreadPool *threadPool,
                                           rtps_UdpDriver *driver,
                                           bool enfUnicast) {
  if (sys_mutex_new(&slw->m_mutex) != ERR_OK) {
#if SLW_VERBOSE
    SLW_LOG("Failed to create mutex \n");
#endif
    return false;
  }
  rtps_Writer_Construct(&slw->writer);
  slw->writer.m_bstateful = false;
  slw->writer.m_attributes = attributes;
  slw->m_packetInfo.srcPort = attributes.unicastLocator.port;
  slw->m_topicKind = topicKind;
  slw->mp_threadPool = threadPool;
  slw->m_transport = driver;
  slw->m_enforceUnicast = enfUnicast;
  slw->m_nextSequenceNumberToSend.high = 0;
  slw->m_nextSequenceNumberToSend.low = 1;
  slw->writer.m_is_initialized = true;
  SequenceNumber_t lastUsed = {0,0};
  slw->m_history = rtps_SimpleHistoryCache_init(lastUsed);
  return true;
}

bool rtps_StatelessWriterT_addNewMatchedReader(struct rtps_StatelessWriter *slw, 
    const struct rtps_ReaderProxy *newProxy) {
#if SLW_VERBOSE && RTPS_GLOBAL_VERBOSE
  SLW_LOG("New reader added with id: ");
  printGuid(newProxy->remoteReaderGuid);
#endif
  bool success = rtps_MemoryPool_add(slw->writer.m_proxies, (void *)newProxy);
  if (!slw->m_enforceUnicast) {
    rtps_StatelessWriter_manageSendOptions(slw);
  }
  return success;
}

void rtps_StatelessWriterT_manageSendOptions(struct rtps_StatelessWriter *slw) {
    uint8_t *ptmp;
    uint8_t *pblk;
    uint8_t *pdata;
    uint32_t offset;
    uint8_t *ptmp2;
    uint8_t *pblk2;
    uint8_t *pdata2;
    uint32_t offset2;
    ReaderProxy *proxy;//????
    ReaderProxy *avproxy;//????
    bool found = false;
    int ret;

  SLW_LOG("Search for Multicast Partners!\n");
  RTPS_MEMORYPOOL_ITER(slw->writer.m_proxies, offset, ptmp, pblk, pdata) {
    proxy = (ReaderProxy *)pdata;
    if (proxy->remoteMulticastLocator.kind == LOCATOR_KIND_INVALID) {
      proxy->suppressUnicast = false;
      proxy->useMulticast = false;
    } else {
      RTPS_MEMORYPOOL_ITER(slw->writer.m_proxies, offset2, ptmp2, pblk2, pdata2) {
        avproxy = (ReaderProxy *)pdata2;
        if (avproxy->remoteMulticastLocator.kind == LOCATOR_KIND_UDPv4 &&
            rtps_Locator_getIp4Address(&avproxy->remoteMulticastLocator).addr ==
                rtps_Locator_getIp4Address(&proxy->remoteMulticastLocator).addr &&
            rtps_Locator_getIp4Address(&avproxy->remoteLocator).addr !=
                rtps_Locator_getIp4Address(&proxy->remoteLocator).addr) {

          if (avproxy->suppressUnicast == false) {
            avproxy->useMulticast = false;
            avproxy->suppressUnicast = true;
            proxy->useMulticast = true;
            proxy->suppressUnicast = true;
            SLW_LOG("Found Multicast Partner!\n");
            ret = memcmp((void *)&avproxy->remoteReaderGuid.entityId,
                         (void *)&proxy->remoteReaderGuid.entityId,
                         sizeof(EntityId_t));
            if (ret != 0) {
              proxy->unknown_eid = true;
              SLW_LOG("Found different EntityIds, using UNKNOWN_ENTITYID\n");
            }
          }
          found = true;
        }
      }
      if (!found) {
        proxy->useMulticast = false;
        proxy->suppressUnicast = false;
      }
    }
  }
}


void rtps_StatelessWriterT_resetSendOptions(struct rtps_StatelessWriter *slw) {
  uint8_t *ptmp;
  uint8_t *pblk;
  uint8_t *pdata;
  uint32_t offset;
  ReaderProxy *proxy;//????

  RTPS_MEMORYPOOL_ITER(slw->writer.m_proxies, offset, ptmp, pblk, pdata) {
    proxy = (ReaderProxy *)pdata;
    proxy->suppressUnicast = false;
    proxy->useMulticast = false;
    proxy->unknown_eid = false;
  }
  rtps_StatelessWriter_manageSendOptions(slw);
}


bool statelessWriter_cmp_guid(void *guid, void *readerproxy)
{
	return rtps_Guid_t_operator_equal(&(((ReaderProxy * )readerproxy)->remoteReaderGuid), guid);
}

void rtps_StatelessWriterT_removeReader(struct rtps_StatelessWriter *slw, const Guid_t *guid) {
  rtps_Lock(&slw->m_mutex);

  rtps_MemoryPool_remove(slw->writer.m_proxies,
		                      statelessWriter_cmp_guid, (void *)guid);

  rtps_StatelessWriter_resetSendOptions(slw);

  rtps_Unlock(&slw->m_mutex);
}

bool statelessWriter_cmp_guidPrefix(void *guidPrefix, void *readerproxy)
{
	return rtps_GuidPrefix_t_operator_equal(&(((ReaderProxy * )readerproxy)->remoteReaderGuid.prefix), guidPrefix);
}

void rtps_StatelessWriterT_removeReaderOfParticipant(struct rtps_StatelessWriter *slw, 
    const GuidPrefix_t *guidPrefix) {
  rtps_Lock(&slw->m_mutex);

	rtps_MemoryPool_remove(slw->writer.m_proxies,
			       statelessWriter_cmp_guidPrefix, (void *)guidPrefix);
  rtps_StatelessWriter_resetSendOptions(slw);

  rtps_Unlock(&slw->m_mutex);
}

const struct rtps_CacheChange *rtps_StatelessWriterT_newChange(struct rtps_StatelessWriter *slw, 
    ChangeKind_t kind, const uint8_t *data, DataSize_t size) {
  if (rtps_StatelessWriter_isIrrelevant(kind)) {
    return NULL;
  }      
  rtps_Lock(&slw->m_mutex);

  if (rtps_SimpleHistoryCache_isFull(slw->m_history)) {
    SequenceNumber_t newMin = rtps_SimpleHistoryCache_getSeqNumMin(slw->m_history);
    (void)rtps_SequenceNumber_t_operator_increase(&newMin);
    if (rtps_SequenceNumber_t_operator_less(&slw->m_nextSequenceNumberToSend, &newMin)) {
      slw->m_nextSequenceNumberToSend = newMin; // Make sure we have the correct sn to send
    }
  }

  struct rtps_CacheChange *result = rtps_SimpleHistoryCache_addChange(slw->m_history, data, size);
  if (slw->mp_threadPool != NULL) {
    rtps_ThreadPool_addWorkload(slw->mp_threadPool, &slw->writer);
  }
  rtps_Unlock(&slw->m_mutex);
  SLW_LOG("Adding new data.\n");
  return result;
}


void rtps_StatelessWriterT_setAllChangesToUnsent(struct rtps_StatelessWriter *slw) {
  rtps_Lock(&slw->m_mutex);

  slw->m_nextSequenceNumberToSend = rtps_SimpleHistoryCache_getSeqNumMin(slw->m_history);

  if (slw->mp_threadPool != NULL) {
    rtps_ThreadPool_addWorkload(slw->mp_threadPool, &slw->writer);
  }

  rtps_Unlock(&slw->m_mutex);
}


void rtps_StatelessWriterT_onNewAckNack(struct rtps_StatelessWriter *slw, 
    const SubmessageAckNack *msg, const GuidPrefix_t *sourceGuidPrefix) {
  // Too lazy to respond
  (void)slw;
  (void)msg;
  (void)sourceGuidPrefix;
}


bool rtps_StatelessWriterT_isIrrelevant(ChangeKind_t kind) {
  // Right now we only allow alive changes
  // return kind == ChangeKind_t::INVALID || (m_topicKind == TopicKind_t::NO_KEY
  // && kind != ChangeKind_t::ALIVE);
  return kind != ALIVE;
}


void rtps_StatelessWriterT_progress(struct rtps_StatelessWriter *slw) {
  // TODO smarter packaging e.g. by creating MessageStruct and serialize after
  // adjusting values Reusing the pbuf is not possible. See
  // https://www.nongnu.org/lwip/2_1_x/raw_api.html (Zero-Copy MACs)

    uint8_t *ptmp;
    uint8_t *pblk;
    uint8_t *pdata;
    uint32_t offset;
    ReaderProxy *proxy;//????
    //bool found = false;

  if (rtps_MemoryPool_isEmpty(slw->writer.m_proxies)) {
    SLW_LOG("Skipping progress. No proxies.\n");
    goto end;
  }
  RTPS_MEMORYPOOL_ITER(slw->writer.m_proxies, offset, ptmp, pblk, pdata){
    proxy = (ReaderProxy *)pdata;
    SLW_LOG("Progess proxy %p.\n",proxy);
    // Do nothing, if someone else sends for me... (Multicast)
    if (proxy->useMulticast || !proxy->suppressUnicast || slw->m_enforceUnicast) {
      rtps_PacketInfo info; 
      info.srcPort = slw->m_packetInfo.srcPort;
      info.buffer = rtps_PBufWrapper_Construct(RTPS_PBW_BY_LENG, 0);
      rtps_MessageFactory_addHeader(info.buffer, &slw->writer.m_attributes.endpointGuid.prefix);
      rtps_MessageFactory_addSubMessageTimeStamp(info.buffer, false);

      rtps_Lock(&slw->m_mutex);
      const struct rtps_CacheChange *next =
          rtps_SimpleHistoryCache_getChangeBySN(slw->m_history, slw->m_nextSequenceNumberToSend);

      if (next == NULL) {
        SLW_LOG("Couldn't get a new CacheChange with SN "
                "(%i,%i)\n",
                slw->m_nextSequenceNumberToSend.high,
                slw->m_nextSequenceNumberToSend.low);
        rtps_Unlock(&slw->m_mutex);
        rtps_PBufWrapper_Destruct(info.buffer);
        return;
      } else {
        SLW_LOG("Sending change with SN (%i,%i)\n",
                slw->m_nextSequenceNumberToSend.high,
                slw->m_nextSequenceNumberToSend.low);
      }

      // Set EntityId to UNKNOWN if using multicast, because there might be
      // different ones...
      // TODO: mybe enhance by using UNKNOWN only if ids are really different
      EntityId_t reid;
      if (proxy->useMulticast && !slw->m_enforceUnicast && proxy->unknown_eid) {
        reid = ENTITYID_UNKNOWN;
      } else {
        reid = proxy->remoteReaderGuid.entityId;
      }
      rtps_MessageFactory_addSubMessageData(info.buffer, next->data, false,
                                            &next->sequenceNumber,
                                            &slw->writer.m_attributes.endpointGuid.entityId,
                                            &reid); // TODO

      rtps_Unlock(&slw->m_mutex);

      // Just usable for IPv4
      // Decide which locator to be used unicast/multicast
      const Locator *locator;
      if (proxy->useMulticast && !slw->m_enforceUnicast) {
        locator = &proxy->remoteMulticastLocator;
        info.destAddr = rtps_Locator_getIp4Address((struct Locator *)locator);
        info.destPort = (Ip4Port_t)locator->port;
      } else {
        locator = &proxy->remoteLocator;
        info.destAddr = rtps_Locator_getIp4Address((struct Locator *)locator);
        info.destPort = (Ip4Port_t)locator->port;
      }
      rtps_UdpDriver_sendPacket(slw->m_transport, &info);
      rtps_PBufWrapper_Destruct(info.buffer);
    }
  }
end:
  (void)rtps_SequenceNumber_t_operator_increase(&slw->m_nextSequenceNumberToSend);
}
